//
//  ExamCollectionViewController.m
//  JPWords
//
//  Created by 梁淑婷 on 2024/7/16.
//

#import "ExamCollectionViewController.h"
#import "ExamCollectionQuestionViewController.h"
#import "ExamPaperTypeListModel.h"
#import "ErrorCorrectionViewController.h"
#import "ExamCollectCateManager.h"
#import "ExamQuestionModel.h"
#import "WordCollectDeleteManager.h"
#import "YNPageViewController.h"


@interface ExamCollectionViewController ()<YNPageViewControllerDataSource,YNPageViewControllerDelegate,JPAPIManagerCallBackDelegate,ExamCollectionQuestionViewControllerDelegate>

@property(nonatomic,strong)YNPageViewController *pageViewController;
@property(nonatomic,strong)NSMutableArray *vcArr;
@property(nonatomic,strong)NSMutableArray *titleArr;
@property(nonatomic,strong)NSMutableArray *dataArr;
@property(nonatomic,strong)ExamCollectCateManager *cateManager;
@property(nonatomic,strong)UILabel *countLabel;
@property(nonatomic,strong)UIView *bottomView;
@property(nonatomic,strong)ExamQuestionModel *selQuestionModel;
@property(nonatomic,assign)NSInteger sel_index;
@property(nonatomic,strong)ExamPaperTypeListModel *selTypeModel;
@property(nonatomic,strong)WordCollectDeleteManager *collectDeleteManager;
@property(nonatomic,assign)CGFloat total_w;

@end

@implementation ExamCollectionViewController


-(ExamCollectCateManager *)cateManager{
    if(!_cateManager){
        _cateManager = [[ExamCollectCateManager alloc]init];
        _cateManager.delegate = self;
    }
    return _cateManager;
}

-(NSMutableArray *)dataArr{
    if(!_dataArr){
        _dataArr = [NSMutableArray array];
    }
    return _dataArr;
}

-(WordCollectDeleteManager *)collectDeleteManager{
    if(!_collectDeleteManager){
        _collectDeleteManager = [[WordCollectDeleteManager alloc]init];
        _collectDeleteManager.delegate = self;
    }
    return _collectDeleteManager;
}

-(NSMutableArray *)vcArr{
    if(!_vcArr){
        _vcArr = [NSMutableArray array];
    }
    return _vcArr;
}

-(NSMutableArray *)titleArr{
    if(!_titleArr){
        _titleArr = [NSMutableArray array];
    }
    return _titleArr;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.total_w = 0;
    [self createUI];
    [self loadCateData];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self popGestureClose];
}

-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [self popGestureOpen];
}

-(void)createUI{
    
    self.customNavigationBar.backgroundColor = [UIColor whiteColor];
    [self.customNavigationBar setTitle:[NSString stringWithFormat:@"%@_收藏夹",self.cateModel.dictDataName]];
    self.view.backgroundColor = UIColorHex(0xF2F7F6);
    self.countLabel = [[UILabel alloc]init];
    self.countLabel.font = JPUIFontInterRegular(15);
    self.countLabel.textAlignment = NSTextAlignmentRight;
    self.countLabel.textColor = KFontGrayColor;
    [self.customNavigationBar addSubview:self.countLabel];
    [self.countLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(@-16);
        make.height.mas_equalTo(@18);
        make.bottom.mas_equalTo(@-13);
    }];
    
    __weak typeof(self)self_weak_ = self;
    UIView *bottomView = [[UIView alloc]init];
    bottomView.backgroundColor = [UIColor whiteColor];
    bottomView.layer.cornerRadius = 58/2.0;
    bottomView.layer.shadowColor = UIColorHex_(0x000000,0.25).CGColor;
    bottomView.layer.shadowOffset = CGSizeMake(0,0);
    bottomView.layer.shadowOpacity = 1;
    bottomView.layer.shadowRadius = 10;
    [self.view addSubview:bottomView];
    [bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(@208);
        make.height.mas_equalTo(@58);
        make.centerX.mas_equalTo(self_weak_.view);
        make.bottom.mas_equalTo(@-35);
    }];
    self.bottomView = bottomView;
    
    NSArray *imageArr = @[@"exam_question_uncollect",@"exam_question_error_list"];
    for (NSInteger i = 0; i < imageArr.count; i++){
        UIButton *btn = [[UIButton alloc]init];
        [btn setImage:[UIImage imageNamed:imageArr[i]] forState:UIControlStateNormal];
        if(i == 0){
            [btn setImage:[UIImage imageNamed:@"exam_question_collect"] forState:UIControlStateSelected];
            btn.selected = YES;
        }
        btn.tag = 666+i;
        [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        [bottomView addSubview:btn];
        [btn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.height.mas_equalTo(@44);
            if(i == 0){
                make.left.mas_equalTo(@30);
            }else{
                make.right.mas_equalTo(@-30);
            }
            make.centerY.mas_equalTo(bottomView);
        }];
    }
    
}

#pragma mark - 屏幕宽度改变
- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator {
    [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
    if(isIPAD){
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            // 获取当前可用宽度并更新布局
            self.currentAvailableWidth = [DeviceUtils currentAvailableWidth];
            self.currentAvailableHeight = [DeviceUtils currentAvailableHeight];
            self.customNavigationBar.frame = CGRectMake(0, 0, self.currentAvailableWidth,kYM_NAVIGATIONBAR_HEIGHT);
            NSInteger index = self.sel_index;
            if (self.pageViewController) {
                [self.pageViewController removeFromParentViewController];
                [self.pageViewController.view removeFromSuperview];
            }
            [self createQuestionViewWithIndex:(index>-1)?index:0];
            
            for (UIViewController *childVC in self.pageViewController.controllersM) {
                if ([childVC isKindOfClass:[ExamCollectionQuestionViewController class]]) {
                    ExamCollectionQuestionViewController *yourChildVC = (ExamCollectionQuestionViewController *)childVC;
                    [yourChildVC refreshWidth];
                }
            }
            
        });
    }
}



#pragma mark - 收藏 错误反馈点击
-(void)btnClick:(UIButton*)button{
    
    NSInteger index = button.tag-666;
    if(index == 0){
        //收藏
        if(self.selQuestionModel&&self.selTypeModel.count.integerValue > 0){
            [self collectOrDeleteQuestionWithModel:self.selQuestionModel];
        }
    }else if (index == 1){
        //错误反馈
        if(self.selQuestionModel&&self.selTypeModel.count.integerValue > 0){
            [self stopHearingPlay];
            ErrorCorrectionViewController *vc = [[ErrorCorrectionViewController alloc]init];
            vc.type = 1;
            vc.questionModel = self.selQuestionModel;
            [self.navigationController pushViewController:vc animated:YES];
        }
    }
    
}


#pragma mark - 获取专项数据
-(void)loadCateData{
    //n1-3 @[@"文字词汇",@"语法",@"阅读",@"听力"];
    //高考 @[@"听力",@"单选",@"阅读",@"写作"]
    //考研 @[@"基础知识",@"阅读",@"写作"]
    self.cateManager.grade = self.cateModel.dictDataId;
    [self.cateManager loadData];
}

#pragma mark - 试题收藏和取消收藏
-(void)collectOrDeleteQuestionWithModel:(ExamQuestionModel*)model{
     //取消
     self.collectDeleteManager.collectId = model.collectId;
     [self.collectDeleteManager loadData];
}


#pragma mark - 创建分类界面
-(void)createQuestionViewWithIndex:(NSInteger)index{
    
    if(self.dataArr.count > 0){
        NSInteger count = self.dataArr.count > 4?4:self.dataArr.count;
        CGFloat jiange = (self.currentAvailableWidth-32-self.total_w)/(count-1);
        if(jiange-16 < 10){
            jiange = 26;
        }
        YNPageConfigration *configration = [YNPageConfigration defaultConfig];
        configration.pageStyle = YNPageStyleTop;
        configration.headerViewCouldScale = NO;
        configration.showTabbar = NO;
        configration.showNavigation = YES;
        configration.scrollMenu = YES;
        configration.aligmentModeCenter = YES;
        configration.showBottomLine = NO;
        configration.haveCutout = YES;
        configration.lineWidthEqualFontWidth = YES;
        configration.menuHeight = 42;
        configration.menuWidth = self.currentAvailableWidth;
        configration.itemLeftAndRightMargin = 32;
        configration.itemMargin = jiange-16;
        configration.normalItemColor = KFontGrayColor;
        configration.selectedItemColor = KThemeColor;
        configration.lineColor = KThemeColor;
        configration.itemFont = JPUIFontPingFangSCRegular(16);
        configration.selectedItemFont = JPUIFontPingFangSCMedium(16);
        configration.lineLeftAndRightMargin = 0;
        configration.lineHeight = 4;
        configration.lineCorner = 2;
        configration.lineBottomMargin = -2;
        configration.bgColor = [UIColor whiteColor];
        configration.suspenOffsetY = kYM_NAVIGATIONBAR_HEIGHT;
        
        self.pageViewController = [YNPageViewController pageViewControllerWithControllers:self.vcArr
                                                                                titles:self.titleArr
                                                                                config:configration];
        self.pageViewController.dataSource = self;
        self.pageViewController.delegate = self;
        
        /// 指定默认选择index 页面
        self.pageViewController.pageIndex = index;
      
        // 作为自控制器加入到当前控制器
        [self.pageViewController addSelfToParentViewController:self];
        
        self.pageViewController.view.frame = CGRectMake(0,kYM_NAVIGATIONBAR_HEIGHT,self.currentAvailableWidth,self.currentAvailableHeight-kYM_NAVIGATIONBAR_HEIGHT);
        
    }
    [self.view bringSubviewToFront:self.bottomView];
}

#pragma mark - YNPageViewControllerDataSource
-(UIScrollView *)pageViewController:(YNPageViewController *)pageViewController pageForIndex:(NSInteger)index {
    ExamCollectionQuestionViewController *vc = pageViewController.controllersM[index];
    vc.grade = self.cateModel.dictDataId;
    vc.index = index;
    vc.delegate = self;
    if(index < self.dataArr.count){
        ExamPaperTypeListModel *model = self.dataArr[index];
        vc.typeModel = model;
    }
    return [vc collectionView];
}

#pragma mark - YNPageViewControllerDelegate
- (void)pageViewController:(YNPageViewController *)pageViewController
                 didScroll:(UIScrollView *)scrollView
                  progress:(CGFloat)progress
                 formIndex:(NSInteger)fromIndex
                   toIndex:(NSInteger)toIndex{
    if(toIndex < self.vcArr.count){
        ExamCollectionQuestionViewController *selvc = self.vcArr[toIndex];
        if(toIndex < self.dataArr.count){
            self.sel_index = toIndex;
            ExamPaperTypeListModel *model = self.dataArr[toIndex];
            self.selTypeModel = model;
            NSArray *darr = selvc.dataArr;
            if(darr.count > 0){
                if(self.selTypeModel.current_index < darr.count){
                    self.selQuestionModel = darr[self.selTypeModel.current_index];
                }else{
                    self.selTypeModel.current_index = 0;
                    self.selQuestionModel = darr[0];
                }
            }
            NSInteger count = self.selTypeModel.current_index;
            if(self.selTypeModel.count.integerValue > 0){
                count = count+1;
            }
            self.countLabel.text = [NSString stringWithFormat:@"%ld/%@",count,self.selTypeModel.count];
            [self stopHearingPlay];
        }
    }
}

- (void)pageViewController:(YNPageViewController *)pageViewController
         didScrollMenuItem:(UIButton *)itemButton
                     index:(NSInteger)index{
    if(index < self.vcArr.count){
        ExamCollectionQuestionViewController *selvc = self.vcArr[index];
        if(index < self.dataArr.count){
            self.sel_index = index;
            ExamPaperTypeListModel *model = self.dataArr[index];
            self.selTypeModel = model;
            NSArray *darr = selvc.dataArr;
            if(darr.count > 0){
                if(self.selTypeModel.current_index < darr.count){
                    self.selQuestionModel = darr[self.selTypeModel.current_index];
                }else{
                    self.selTypeModel.current_index = 0;
                    self.selQuestionModel = darr[0];
                }
            }
            NSInteger count = self.selTypeModel.current_index;
            if(self.selTypeModel.count.integerValue > 0){
                count = count+1;
            }
            self.countLabel.text = [NSString stringWithFormat:@"%ld/%@",count,self.selTypeModel.count];
        }
    }
    
}

#pragma mark - 暂停听力播放
-(void)stopHearingPlay{
    for(NSInteger i = 0; i< self.vcArr.count;i++){
        ExamCollectionQuestionViewController *selvc = self.vcArr[i];
        if(selvc.typeModel&&selvc.typeModel.typeId.integerValue == 33){
            [selvc stopHearingPlay];
        }
    }
}


#pragma mark - ExamCollectionQuestionViewControllerDelegate
-(void)pageScroll:(ExamCollectionQuestionViewController *)vc andOptionsModel:(ExamQuestionModel *)questionModel andIndex:(NSInteger)current_index{
    self.selQuestionModel = questionModel;
    NSInteger count = current_index;
    if(self.selTypeModel.count.integerValue > 0){
        count = count+1;
    }
    self.countLabel.text = [NSString stringWithFormat:@"%ld/%@",count,self.selTypeModel.count];
    self.selTypeModel.current_index = current_index;
    if(self.sel_index < self.dataArr.count){
        [self.dataArr replaceObjectAtIndex:self.sel_index withObject:self.selTypeModel];
    }
}

-(void)firstRefresh:(ExamCollectionQuestionViewController *)vc andModel:(ExamQuestionModel *)questionModel{
    if(!self.selQuestionModel){
        self.selQuestionModel = questionModel;
    }
}


#pragma mark - JPAPIManagerCallBackDelegate
-(void)managerCallDLDLAPIDidSuccess:(JPAPIBaseManager *)manager{
    
    if([manager isEqual:self.cateManager]){
        NSDictionary *dic = manager.response.content;
        NSArray *arr = [ExamPaperTypeListModel mj_objectArrayWithKeyValuesArray:dic[@"data"]];
        self.total_w = 0;
        for(NSInteger i = 0;i < arr.count;i++){
            ExamPaperTypeListModel *model = arr[i];
            model.current_index = 0;
            if(i == 0){
                self.selTypeModel = model;
            }
            [self.dataArr addObject:model];
            [self.titleArr addObject:model.typeName];
            ExamCollectionQuestionViewController *vc = [[ExamCollectionQuestionViewController alloc] init];
            [self.vcArr addObject:vc];
            if(i < 4){
                CGFloat w = [self getStringWidthWithText:model.typeName?model.typeName:@"" font:JPUIFontPingFangSCMedium(16) viewHeight:42];
                self.total_w = self.total_w+w;
            }
        }
        if(self.dataArr.count > 0){
            self.sel_index = 0;
            if(self.selTypeModel.count.integerValue > 0){
                self.countLabel.text = [NSString stringWithFormat:@"1/%@",self.selTypeModel.count];
            }else{
                self.countLabel.text = [NSString stringWithFormat:@"0/%@",self.selTypeModel.count];
            }
        }else{
            self.sel_index = -1;
            self.countLabel.text = @"0/0";
        }
        [self createQuestionViewWithIndex:0];
    }
    
    if([manager isEqual:self.collectDeleteManager]){
        NSDictionary *dic = manager.response.content;
        if(dic[@"message"]){
            [JPProgressHUD showMsg:dic[@"message"]];
        }
        self.selTypeModel.count = [NSString stringWithFormat:@"%ld",self.selTypeModel.count.integerValue > 0?self.selTypeModel.count.integerValue-1:0];
        self.selTypeModel.current_index = 0;
        [self.dataArr replaceObjectAtIndex:self.sel_index withObject:self.selTypeModel];
        if(self.selTypeModel.count.integerValue > 0){
            self.countLabel.text = [NSString stringWithFormat:@"1/%@",self.selTypeModel.count];
        }else{
            self.countLabel.text = @"0/0";
        }
        if((self.sel_index > -1)&&(self.sel_index < self.vcArr.count)){
            ExamCollectionQuestionViewController *selvc = self.vcArr[self.sel_index];
            NSMutableArray *arr = [NSMutableArray arrayWithArray:selvc.dataArr];
            for(NSInteger i = 0;i < arr.count;i++){
                ExamQuestionModel *model = arr[i];
                if([model.collectId isEqualToString:self.collectDeleteManager.collectId]){
                    [arr removeObjectAtIndex:i];
                    break;
                }
            }
            selvc.dataArr = arr;
            [selvc refreshData];
            
        }
        
    }
    
}

-(void)managerCallDLDLAPIDidFailed:(JPAPIBaseManager *)manager{
    if(manager.errorMessage){
        [JPProgressHUD showMsg:manager.errorMessage];
    }
}


@end
